#include "GenOpt.h"
#include <QByteArray>
#include <QCoreApplication>
#include <QDataStream>
#include <QDir>
#include <QFileInfo>
#include <qstringview.h>

QString CGenOpt::DoubleToHexString(double data) {
  double num = data;
  QByteArray ba =
      QByteArray::fromRawData(reinterpret_cast<char *>(&num), sizeof(num));
  QString hex = ba.toHex();
  return hex;
}

double CGenOpt::HexStringToDouble(QString str) {
  QByteArray hexBytes = QByteArray::fromHex(str.toLatin1());
  QDataStream stream(hexBytes);
  stream.setByteOrder(QDataStream::LittleEndian); // 根据需要设置字节序
  double data = 0.0;
  stream >> data;
  return data;
}

QString CGenOpt::GetFileNameFromPath(QString path) {
  QFileInfo fileInfo(path);
  return fileInfo.baseName();
}

QString CGenOpt::GetRadarFileName(QString video_name) {
  QFileInfo fileInfo(video_name);
  QString file_video = fileInfo.baseName();
  int index = file_video.indexOf("[");
  QString file_radar = file_video;
  if (index != -1) {
    file_radar = file_video.mid(0, index);
  }
  return fileInfo.absolutePath() + "/" + file_radar + ".csv";
}

uint32_t CGenOpt::SearchAllFileInPath(QString path, QStringList &file_list) {
  QDir dir(path);
  if (!dir.exists()) {
    return 0;
  }
  dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks);
  dir.setSorting(QDir::DirsFirst);
  QFileInfoList list = dir.entryInfoList();
  int i = 0;
  bool is_dir;
  do {
    QFileInfo file_info = list.at(i);
    if ((file_info.fileName() == ".") || (file_info.fileName() == "..")) {
      i++;
      continue;
    }

    is_dir = file_info.isDir();
    if (is_dir) {
      // 进行递归
      CGenOpt::SearchAllFileInPath(file_info.filePath(), file_list);
    } else {
      // 获取文件后缀并获取所选包含类型，若存在包含类型且后缀相同，则添加
      QString absolute_file_path = file_info.absoluteFilePath();
      QString suffix = file_info.suffix();
      QString file_tmp = file_info.absoluteFilePath();
      if ((QString::compare(suffix, QString("avi"), Qt::CaseInsensitive) ==
           0) ||
          (QString::compare(suffix, QString("mkv"), Qt::CaseInsensitive) ==
           0) ||
          (QString::compare(suffix, QString("mp4"), Qt::CaseInsensitive) ==
           0) ||
          (QString::compare(suffix, QString("mov"), Qt::CaseInsensitive) ==
           0) ||
          (QString::compare(suffix, QString("h264"), Qt::CaseInsensitive) ==
           0)) {
        QString absolute_file_path = file_info.absoluteFilePath();
        file_list.append(absolute_file_path);
      }
    }
    i++;
  } while (i < list.size());
  return file_list.size();
}

QString CGenOpt::GetExePath() {
  QDir dir(QCoreApplication::applicationDirPath());
  return dir.absolutePath();
}

int CGenOpt::QStringToChar(QString str, char *buf, uint32_t buf_len) {
  QByteArray byte_array = str.toLocal8Bit();
  if (byte_array.size() + 1 > buf_len) {
    return -1;
  }
  strcpy(buf, byte_array.data());
  buf[byte_array.size()] = '\0';
  return byte_array.size();
}
